package com.huatai.range.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huatai.common.util.BeanUtil;
import com.huatai.common.util.ObjectUtil;
import com.huatai.range.entity.TbTrialInfoEntity;
import com.huatai.range.entity.TrialTableEntity;
import com.huatai.range.feign.TrialInfoClient;
import com.huatai.range.request.CreateTabRequest;
import com.huatai.range.mapper.CreateTabMapper;
import com.huatai.range.service.CreateTabService;
import com.huatai.range.service.TrialTableService;
import com.huatai.range.vo.IsExistVo;
import com.huatai.range.vo.SuccessVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.stream.Collectors;

import static com.huatai.range.common.constant.GISConstant.*;

/**
 * @ClassName CreateTabServiceImpl
 * @Description TODO
 * @Author luoxc
 * @Date 2023/4/17 15:17
 * @Version 1.0
 */
@Slf4j
@Service
public class CreateTabServiceImpl implements CreateTabService {

	@Autowired
	private CreateTabMapper createTabMapper;

	@Autowired
	private TrialTableService trialTableService;

	@Autowired
	private TrialInfoClient trialInfoClient;

	private final static List<String> TAB_NAME_LIST = Arrays.asList(GIS_RANGE, GIS_PATH, GIS_POI, GIS_EFFECT);

	/**
	 * 删除表
	 *
	 * @param tabName
	 * @return
	 */
	@Transactional(isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
	@Override
	public SuccessVo dropTab(String tabName) {
		try {
			trialTableService.remove(Wrappers.<TrialTableEntity>lambdaQuery().eq(TrialTableEntity::getTabName, tabName));
			createTabMapper.dropTab(tabName);
			log.info("表:{} 删除成功", tabName);
			return new SuccessVo(true);
		} catch (Exception e) {
			log.info("表:{} 删除失败", tabName);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return new SuccessVo(false);
		}
	}

	/**
	 * 查看表是否存在
	 *
	 * @param tabName
	 * @return
	 */
	@Override
	public IsExistVo existTab(String tabName) {
		return new IsExistVo(createTabMapper.existTab(tabName) > 0);
	}

	/**
	 * 查询库中所有表
	 * @return
	 */
	@Override
	public List<String> publicNames() {
		return createTabMapper.publicNames();
	}

	/**
	 * 一键建表
	 *
	 * @param createTabRequest
	 * @return
	 */
	@Transactional(isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
	@Override
	public SuccessVo create(CreateTabRequest createTabRequest) {

		try {
			if (!TAB_NAME_LIST.contains(createTabRequest.getTabType())) {
				log.info("表类型不存在");
				throw new RuntimeException();
			}
			createTab(createTabRequest);
			saveTrialTab(createTabRequest);
			log.info("新增成功");
			return new SuccessVo(true);
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			log.info(e.getMessage());
			return new SuccessVo(false);
		}
	}

	/**
	 * 保存试验表
	 *
	 * @param createTabRequest
	 */
	private void saveTrialTab(CreateTabRequest createTabRequest) {
		TrialTableEntity tableEntity = BeanUtil.copyProperties(createTabRequest, TrialTableEntity.class);
		String trialId = tableEntity.getTrialId();
		TbTrialInfoEntity trialInfo = trialInfoClient.getOne(trialId).getData();
		if (ObjectUtil.isEmpty(trialInfo)) {
			log.info("{}: 试验id不存在！", trialId);
			throw new RuntimeException();
		} else if (!trialInfo.getTrialName().equals(tableEntity.getTrialName())) {
			log.info("试验id: {}和试验名称: {}不匹配！", trialId, tableEntity.getTrialName());
			throw new RuntimeException();
		}
		List<TrialTableEntity> tabs =
			trialTableService.list(Wrappers.<TrialTableEntity>lambdaQuery().eq(TrialTableEntity::getTrialId, trialId));
		if (tabs.isEmpty()) {
			trialTableService.save(tableEntity);
		} else {
			List<String> aliasList = tabs.stream().map(TrialTableEntity::getAlias).collect(Collectors.toList());
			if (!aliasList.contains(tableEntity.getAlias())) {
				trialTableService.save(tableEntity);
			} else {
				log.info("{}:表别名重复", tableEntity.getAlias());
				throw new RuntimeException();
			}
		}
	}

	/**
	 * 创建表
	 *
	 * @param createTabRequest
	 */
	public void createTab(CreateTabRequest createTabRequest) {
		switch (createTabRequest.getTabType()) {
			case GIS_RANGE:
				createTabMapper.createRange(createTabRequest.getTabName());
				break;
			case GIS_PATH:
				createTabMapper.createPath(createTabRequest.getTabName());
				break;
			case GIS_POI:
				createTabMapper.createPoi(createTabRequest.getTabName());
				break;
			case GIS_EFFECT:
				createTabMapper.createEffect(createTabRequest.getTabName());
				break;
			default:
				break;
		}
	}
}
